import pymongo
from copy import deepcopy

class Mongo:
    def __init__(self, db_name):
        self.db_name = db_name
        self.client = pymongo.MongoClient("mongodb://localhost:27017/")
        self.db = self.client[self.db_name]
          
    def insert_data(self, collection_name, dict_data):
        """将一个字典插入指定集合"""
        collection = self.db[collection_name]
        collection.insert_one(dict_data)
        
    def find_data_list(self, collection_name, dict_query, 
                       all_last='last', dict_filter=None):
        """查找数据，返回全部格式为list或最后一条为字典，"""
        collection = self.db[collection_name]
        list_result = list(collection.find(dict_query, dict_filter))
        if list_result:
            if all_last == 'all':
                return list_result
            elif all_last == 'last':
                return list_result[-1]
        else:
            return None
        
    def update_data(self, collection_name, dict_query, new_data_dict, one_all='one'):
        """更新数据,前提是数据存在，不存在不能修改，也不会报错"""
        collection = self.db[collection_name]
        new_values = {"$set": new_data_dict}
        query_result = self.find_data_list(collection_name, dict_query, 'last')
        if query_result:
            if one_all == 'one':
                collection.update_one(dict_query, new_values)
            elif one_all == 'all':
                collection.update_many(dict_query, new_values)
        else:
            _ = deepcopy(dict_query)
            _.update(new_data_dict)
            self.insert_data(collection_name, _)

    def replace_data(self, collection_name, new_data_dict, dict_query={}):
        """替换整个表格"""
        collection = self.db[collection_name]
        collection.delete_many(dict_query)
        collection.insert_one(new_data_dict)
        return print('已替换')